package com.wmz.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wmz.domain.SysMenu;
import com.wmz.mapper.SysMenuMapper;
import com.wmz.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

@Service
@CacheConfig(cacheNames = "com.wmz.service.impl.SysMenuServiceImpl")
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService{
    @Autowired
    private SysMenuMapper sysMenuMapper;
    /**
     * 根据用户ID查询菜单集合
     * @param userId
     * @return
     */
    @Override
    @Cacheable(key = "#userId")
    public Set<SysMenu> queryUserMenus(Long userId) {
        //获取用户菜单集合
        Set<SysMenu> sysMenuSet = sysMenuMapper.selectUserMenusByUserId(userId);
        //判断是否为空
        if(!CollectionUtils.isEmpty(sysMenuSet) && sysMenuSet.size() != 0) {
            // 将菜单转换为树结构
            // 两种情况：
            // 1.只有两层
            // 2.大于两层
            sysMenuSet = translateMenusToTree(sysMenuSet,0L);
        }
        return sysMenuSet;
    }

    /**
     * 将集合菜单转换为树结构
     * @param sysMenuSet 转换的集合菜单
     * @param pid 父节点ID
     * @return
     */
    private Set<SysMenu> translateMenusToTree(Set<SysMenu> sysMenuSet, Long pid) {
        // 获取根节点集合
        Set<SysMenu> roots = sysMenuSet.stream()
                .filter(menu -> menu.getParentId().equals(pid))
                .collect(Collectors.toSet());
        // 只有两层
        /*roots.forEach(root -> {
            // 获取子节点集合
            Set<SysMenu> children = menus.stream()
                    .filter(menu -> menu.getParentId().equals(root.getMenuId()))
                    .collect(Collectors.toSet());
            root.setList(children);
        });*/
        //大于两层：循环遍历父节点集合，根据指定父节点id查询子节点集合
        roots.forEach(root -> root.setMenuList(translateMenusToTree(sysMenuSet,root.getMenuId())));
        return roots;
    }
}
